<template>
  <div class="map" id="map"></div>
  <div class="btns">

    <el-checkbox v-model="item.modelValue" :label="item.label" @change="change(item)" v-for="item in changeBox"/>
 

  </div>
</template>

<script setup>

import * as L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import './utils/Leaflet.canvaslabel'
// import './utils/leaflet.canvas-markers'
import HelloWorld from './components/HelloWorld.vue'
import { computed, onMounted, ref, createVNode, render, reactive } from 'vue'
// import VueSvg from './assets/vue.svg'
import './utils/L.LabelTextCollision'
// import {CanvasLabel} from "@panzhiyue/leaflet-canvaslabel"
// import {CanvasMarkerLayer} from "@panzhiyue/leaflet-canvasmarker"
import 'leaflet-rotatedmarker'
import './utils/leaflet.contextmenu'
import {LeafletDrawLonlatLine} from "leaflet-lonlat-gridlines";
import './utils/Control.MiniMap'

const changeBox = reactive([
  { modelValue: false, label: 'a'},
  { modelValue: false, label: 'b'},
  { modelValue: true, label: 'c'},
  { modelValue: false, label: 'd'}
])

const change = (a,b) => {
  console.log(a,b)
}

const value = ref()
const options = [
  {
    value: '船舶信息',
    label: '船舶信息',
  },
  {
    value: '人员信息',
    label: '人员信息',
  },
  {
    value: '历史轨迹显示',
    label: '历史轨迹显示',
    children: [
      {
        value: '10分钟',
        label: '10分钟',
      },
      {
        value: '1小时',
        label: '1小时',
      },
      {
        value: '6小时',
        label: '6小时',
      },
    ],
  },
]

// let zoom = computed(() => {
//   if(map) {
//     return map.getZoom()
//   }
//   return 
// })
const zoom = ref()
let lonLatGridLines
onMounted(() => {

  // //矢量文本标签渲染器
  // var canvasLabel = new L.CanvasLabel({
  //   defaultLabelStyle: {
  //     collisionFlg: true,
  //     scale: 1,
  //     // strokeStyle: "white",
  //     strokeStyle: "#fff",
  //     fillStyle: "rgba(0,0,0,1)",
  //     lineWidth:3,
      
  //   }
  // })

  window.map = L.map('map', {
    center: [22, 118], // 地图中心
    crs: L.CRS.EPSG4326,
    zoom: 6,
    minZoom: 1,
    maxZoom: 15,
    //限制显示地理范围
    maxBounds: L.latLngBounds(L.latLng(-180, -180), L.latLng(180, 180)),
    // renderer : canvasLabel,
    contextmenu: true, //右键菜单
    logoControl: false, // 隐藏logo版权
    zoomControl: false, // 缩放控件
    attributionControl: false // 隐藏文字版权
  })
  addLayer()
  function addLayer() {
    // 矢量图+注记
    let mapTypes = ['vec_c', 'cva_c'];  
    // 天地图 token
    let tdtToken = 'ce62df9dd155c78d0d3a96652168cc71';
    let layers = [];
    for(let i = 0, len = mapTypes.length; i < len; i++) {
        let tdtUrl = `http://t0.tianditu.gov.cn/DataServer?T=${mapTypes[i]}&x={x}&y={y}&l={z}&tk=${tdtToken}`;
        let layer = L.tileLayer(tdtUrl, {
            zoomOffset: 1,// 注意如果是 web 墨卡托投影(EPSG:3857) 请改为 0
            noWrap: true,
            bounds: [[-90, -180], [90, 180]]
        });
        layers.push(layer);
    }
    // LayerGroup 对象
    let tdtLayerGroup = L.layerGroup(layers).addTo(map);
    // 获取地图 id，可用于获取地图对象
    let leafletId = tdtLayerGroup._leaflet_id;
}

 


  function close() {
    contextMenu.close()
  }

  // 创建自定义辅助菜单
  var contextMenu = L.popup({
    offset: [0, -15],
    className: 'menu-popup-content',
    offset: [80,200]
  });
  let div = document.createElement('div')

  let Vnode = createVNode(HelloWorld, {
    closeFN: close
  })
  render(Vnode, div)
  let markerData = [
    { lat: 23, lng: 113, name: 'marker1'},
    { lat: 23, lng: 113.4, name: 'marker2'}
  ]
  markerData.forEach(item => {
    
    let marker = L.marker([item.lat, item.lng]).addTo(map).on('contextmenu', e => {
      // 阻止默认的右键菜单
      e.originalEvent.preventDefault();
      console.log(e)
      // // 设置菜单内容和位置
      contextMenu.setLatLng(e.latlng)
      .setContent(div)
      .openOn(map);
    })
  })


  // // 创建标记并添加到地图上
  // var marker = L.marker([23, 113]).addTo(map).on('contextmenu', (e) => {
  //   // 阻止默认的右键菜单
  //   e.originalEvent.preventDefault();
  //     // 设置菜单内容和位置
  //     contextMenu.setLatLng(e.latlng)
  //     .setContent(div)
  //     .openOn(map);
  // })
  

  // // 监听地图上的 contextmenu 事件
  // map.on('contextmenu', function(e) {
  //   // 阻止默认的右键菜单
  //   e.originalEvent.preventDefault();

  //   // 设置菜单内容和位置
  //   contextMenu.setLatLng(e.latlng)
  //     .setContent('<p>Custom Menu</p><ul><li>Option 1</li><li>Option 2</li></ul>')
  //     .openOn(map);
  // });

})


function init() {
  removeLayer()
  for (let i = 0; i < 300; i++) {
    let d = getRandomLatLng(map)
    var marker = L.marker(d, {
      icon: icon,
      rotationAngle: Math.random() * 180,
      contextmenu: true,
      contextmenuInheritItems: false,
      contextmenuItems: [
        {
          text: '显示坐标',
          callback: showCoordinates,
          contextmenuItems: [
          {
            text: '作为地图中心',
            callback: centerMap
          },
          ]
        },
        
        {
            text: '作为地图中心',
            callback: centerMap
        },
        '-', {
            text: '地图放大',
            // icon: './images/zoom-in.png',
            callback: zoomIn
        }, {
            text: '地图缩小',
            // icon: './images/zoom-out.png',
            callback: zoomOut
        }
      ],
    })
    // .bindTooltip('某某船'+ i, {
    //   className: 'typhname-tooltip',
    //   direction: 'right', // 向右
    //   opacity: 0.7 ,
    //   offset: L.point(10, 0), // 偏移
    //   permanent: true // 永久提示
    // }).openTooltip()
    .addTo(map)
    markers.push(marker)
    
    let label = L.circleMarker(d,
    {   color: 'transparent',
        fillColor: 'transparent',
        // opacity: 0,
        radius: 0,
        labelStyle: {
          rotation: 0,
          minZoom: 4,
          defaultHeight: 30,
          text: '某某船'+i,
          offsetX: 20,
          offsetY: 20,
        }
      }
    ).addTo(map)
    labels.push(label)
  }
}

function showCoordinates(e) {
    alert(e.latlng);
}

function centerMap(e) {
    map.panTo(e.latlng);
}

function zoomIn(e) {
    map.zoomIn();
}

function zoomOut(e) {
    map.zoomOut();
}

function removeLayer() {
  if (markers.length == 0) return
  for (var i = 0; i < markers.length; i++) {
    var marker = markers[i];
    let label = labels[i]
    map.removeLayer(label);
    map.removeLayer(marker);
  }
  labels = []
  markers = []
}
function reset() {
  var bounds = map.getBounds();
  let mapZoom = map.getZoom();
  zoom.value = mapZoom
  for (var i = 0; i < markers.length; i++) {
    var marker = markers[i];
    var markerLatLng = marker.getLatLng();
    if (mapZoom <= 3) {
      map.removeLayer(marker);
      continue
    }
    // 检查标记是否在可视范围内
    if (bounds.contains(markerLatLng)) {
      // 在可视范围内，进行渲染操作 
      marker.addTo(map);
    } else {
      // 不在可视范围内，移除标记
      map.removeLayer(marker);
    }
  }
}


const show = () => {
  // init()
  /** 初始化话的时候，触发一次绘制*/
  lonLatGridLines.drawLonlatTileGrid();
/** 添加绘制地图事件（即拖动地图时，清除上一次的图层的同时绘制新的图层）*/
lonLatGridLines.addDrawEvent(); 
}
const hide = () => {
  // removeLayer()
  lonLatGridLines.removeDrawEvent()
}

//生成随机点
const getRandomLatLng = map => {
  let bounds = map.getBounds(),
    southWest = bounds.getSouthWest(),
    northEast = bounds.getNorthEast(),
    lngSpan = northEast.lng - southWest.lng,
    latSpan = northEast.lat - southWest.lat;

  return L.latLng(
    southWest.lat + latSpan * Math.random(),
    southWest.lng + lngSpan * Math.random()
  );
}
</script>

<style>
 @import url('./utils/leaflet.contextmenu.css');
 @import url('./utils/Control.MiniMap.css');
.map {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.btns {
  position: absolute;
  left: 200px;
  top: 200px;
  z-index: 99;
}
</style>